<template>
    <l-layout class="l-tab-page" :top="formHeight + 12">
        <template #top>
            <l-query :span="7" :labelWidth="150" :height.sync="formHeight" :items="formItems" :formData="formData"
                :loading="tableLoading" @search="handleSearch">
                <template #name>
                    <el-input v-model="formData['name']" :placeholder="$t('请输入')" clearable @change="handleSearch" />
                </template>
                <template #categorycode>
                    <l-select :options="categoryCodeOptions" v-model="formData['categorycode']" @change="handleSearch" />
                </template>
                <template #dealstatuscode>
                    <l-select :options="statusOptions" v-model="formData['dealstatuscode']" @change="handleSearch" />
                </template>
            </l-query>
        </template>
        <l-panel style="padding-top:0;">
            <template #toolLeft>
                <div class="l-panel--item">
                    <el-button type="primary" size="mini" icon="el-icon-plus" @click="addPolicyFile">新增</el-button>
                </div>
                <div class="l-panel--item" style="margin-left: 5px;">
                    <l-excel-btns></l-excel-btns>
                </div>
                <!-- <div class="l-panel--item" style="margin-left: 5px;">
                    <el-button type="danger" size="mini" icon="el-icon-delete" @click="batchDelete"
                        :disabled="selection.length === 0">批量删除</el-button>
                </div> -->
            </template>
            <template #toolRight>
                <l-tool-btns :hasAdd="false" :hasTableSetting="true" @setting="lr_handleSettingTable"> </l-tool-btns>
            </template>
            <l-table ref="mainTable" @select="handleSelect" @selectAll="handleSelectAll" :isMultiSelect="true"
                :loading="tableLoading" :columns="columns" :dataSource="tableData" :isPage="true" :pageTotal="tableTotal"
                :tablePage.sync="tableCurrentPage" @loadPageData="turnTablePage">
                <template #name="scope">
                    <a @click="openFile(scope.row.document)">{{ scope.row.name || '---' }}</a>
                </template>
                <template #label="{ row }">
                    {{ row.labelList.length === 0 ? "---" : labelListToLabels(row.labelList) }}
                </template>
                <template v-for="(col, index) in lr_tableColumnsByToLabel(columns)" v-slot:[col.prop]="scope">
                    <l-value-to-label :value="scope.row[col.prop]" :type="col.dataType" :code="col.dataCode"
                        :valueKey="col.valueKey" :labelKey="col.labelKey" :options="col.options" :format="col.format"
                        :setting="col.setting" :key="index"></l-value-to-label>
                </template>
                <l-table-btns :btns="tableBtns" :filterBtns="filterBtns" @click="lr_handleTableBtnClick"
                    :btnNum="6"></l-table-btns>
            </l-table>
        </l-panel>
        <DialogForm ref="dialogForm" @refresh="loadTableData" :disabled="isDisabled" />
        <l-dialog title="详情" :visible.sync="formVisible" :height="700" :width="1000" @close="handleCloseForm"
            :hasBtns="true" :showMinBtn="false" :showFullscreenBtn="false">
            <template v-if="formVisible && selectId">
                <l-file-preview :selectFile="selectFile"></l-file-preview>
            </template>
        </l-dialog>
        <l-dialog title="文件列表" :width="400" :modal="false" :hasBtns="false" :hasHeight="false" :hasMinBtn="true"
            placement="bottom-right" :visible.sync="loadVisible" class="file-list-dialog">
            <upload-file-list :uploadingFiles="uploadingFiles" :handleFilePreview="handleFilePreview" />
        </l-dialog>
        <l-dialog title="文件预览" :visible.sync="previewVisible" width="1000px" :height="800">
            <div v-if="!isAllowed" class="desc">
                <div class="icon">
                    <svg t="1706076437100" class="icon" viewBox="0 0 1024 1024" version="1.1"
                        xmlns="http://www.w3.org/2000/svg" p-id="1947" id="mx_n_1706076437101" width="16" height="16">
                        <path
                            d="M512 97.52381c228.912762 0 414.47619 185.563429 414.47619 414.47619s-185.563429 414.47619-414.47619 414.47619S97.52381 740.912762 97.52381 512 283.087238 97.52381 512 97.52381z m0 73.142857C323.486476 170.666667 170.666667 323.486476 170.666667 512s152.81981 341.333333 341.333333 341.333333 341.333333-152.81981 341.333333-341.333333S700.513524 170.666667 512 170.666667z m36.571429 268.190476v292.571428h-73.142858V438.857143h73.142858z m0-121.904762v73.142857h-73.142858v-73.142857h73.142858z"
                            p-id="1948" fill="#ffaa00"></path>
                    </svg>
                </div>
                <div class="tip">该类型文件不支持预览，请点击下方下载按钮下载文件进行预览</div>
            </div>
            <iframe v-else-if="previewUrl != ''" :src="previewUrl" class="l-iframe" ref="iframe" frameborder="0"></iframe>
            <template #btns>
                <el-button size="mini" icon="el-icon-down" type="primary" @click="
                    downFile(`${previewFileId}`)
                    ">下载</el-button>
            </template>
        </l-dialog>
    </l-layout>
</template>
  
<script>
import UploadFileList from "@/core/components/upload-preview/lrUploadFileList.vue";
import { tableColmuns, formColmuns, api, formData } from "./columns";
import DialogForm from "./DialogForm"
export default {
    components: {
        DialogForm,
        UploadFileList
    },
    data() {
        return {
            // 控制dialogForm组件中的form表单是否禁用，默认禁用
            isDisabled: true,
            lr_isPage: true,
            formHeight: 44,
            formData: formData,
            formItems: formColmuns,
            tableLoading: true,
            tableData: [],
            tableTotal: 0,
            tableCurrentPage: 1,
            tablePageSize: 50,
            columns: tableColmuns,
            tableBtns: [
                { prop: 'Download', label: '下载' },
                { prop: 'Edit', label: '编辑' },
                { prop: 'Delete', label: '删除' },
            ],
            formVisible: false,
            formTitle: '',
            formEditRow: null,
            formEdit: false,
            selectFile: {},
            labelList: [],
            isFirst: true,
            //
            fileExt: "",
            loadVisible: false,
            uploadingFiles: [],
            previewFileId: "",
            previewUrl: "",
            previewVisible: false,
            selection: []
        }
    },
    computed: {
        selectId() {
            return this.selectFile.f_Id || ""
        },
        categoryCodeOptions() {
            return this.lr_dataItemOptions(this.lr_dataItem['category_code'])
        },
        statusOptions() {
            return this.lr_dataItemOptions(this.lr_dataItem['status'])
        },
        isAllowed() {
            return this.fileExt === "pdf"
        }
    },
    created() {

    },
    mounted() {
        this.lr_loadDataItem('category_code');
        this.lr_loadDataItem('status');
        this.lr_loadDataItem('label');
        this.init()

    },
    methods: {
        batchDelete() {
            this.$confirm('是否确定批量删除选中数据?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleSelect(checked, row, rowIndex) {
            this.selection = this.$refs.mainTable.getSelected()
        },
        handleSelectAll(checked) {
            this.selection = this.$refs.mainTable.getSelected()
        },
        labelListToLabels(labelList) {
            let labels = '';
            labelList.length && labelList.forEach(i => {
                labels += `,${i.name}`;
            })
            labels = labels.slice(1)
            return labels;
        },
        async addPolicyFile() {
            this.isDisabled = false;
            this.$refs.dialogForm.open({}, {
                labelList: this.labelList,
                isFirst: this.isFirst,
                isAdd: true
            });
            this.isFirst = false;
        },
        // 点击下载按钮的回调
        handleDownload(index, row) {
            if (!row.document) {
                this.$message({
                    type: 'info',
                    message: this.$t('文件不存在!')
                })
                return
            }
            this.$confirm(this.$t('是否下载该文档?'), this.$t('提示'), {
                cancelButtonText: this.$t('取消'),
                confirmButtonText: this.$t('确定'),
                type: 'warning'
            }).then(async () => {
                const api = window.$crud(`system/annexesfile/${row.document}/list`);
                const list = await this.$awaitWraper(api.getInfo());
                console.log("🚀 ~ list:", list)

                for (const k of list) {
                    console.log("🚀 ~ k:", k)
                    this.$downFile(
                        `${this.apiUrl}system/annexesfile/${k.f_Id}?token=${this.token}`
                    );
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('已取消!')
                })
            })
        },
        // 编辑按钮的回调
        handleEdit(index, row) {
            let labels = "";
            row.labelList.forEach(i => {
                labels += `,${i.type}`;
            })
            labels = labels.slice(1);
            // row.labels = labels;
            this.$set(row, "labels", labels)
            this.isDisabled = false;
            this.$refs.dialogForm.open(row, { isAdd: false, labelList: this.labelList, isFirst: this.isFirst, });
            this.isFirst = false;
        },
        // 删除按钮的回调
        handleDelete(index, row) {
            this.$confirm(this.$t('是否删除该条数据?'), this.$t('提示'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
            }).then(async () => {
                let api = window.$crud("standardplan/info");
                await api.remove(row.id)
                this.$message({
                    type: 'success',
                    message: this.$t('删除成功!')
                })
                this.loadTableData()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('已取消删除!')
                })
            })
        },
        async init() {
            this.loadTableData()
            // 获取标签的列表
            let labelapi = window.$crud("label");
            let res = await labelapi.getPage({
                page: "1",
                rows: "10",
                type: "plan"
            })
            res.data.data.rows.forEach(i => {
                this.labelList.push({
                    name: i.name,
                    id: i.id
                })
            })
        },
        filterBtns(row, btns) {
            return btns
        },
        handleSearch() {
            this.loadTableData()
        },
        turnTablePage({ rows }) {
            this.tablePageSize = rows
            this.loadTableData(true)
        },
        async loadTableData(isNotFirst) {
            if (!isNotFirst) {
                this.tableCurrentPage = 1
            }
            this.tableLoading = true
            let formData = this.$deepClone(this.formData)
            formData.rows = this.tablePageSize
            formData.page = this.tableCurrentPage
            formData.sidx = 'modifyTime'
            formData.sord = 'DESC'
            let data = await this.$awaitWraper(api.getPage(formData))
            if (data != null) {
                this.tableData = data.rows
                this.tableData.map(i => {
                    i.label = "";
                    i.labelList.length !== 0 && i.labelList.forEach(j => {
                        i.label += `,${j.name}`
                        // this.$set(i, "label", j.name)
                    })
                    if (i.label !== "") {
                        i.label = i.label.slice(1)
                        // this.$set(i, "label", i.label.slice(1))
                    }
                })
                this.tableTotal = data.records
            }
            else {
                this.tableTotal = 0
                this.tableData = []
            }
            this.tableLoading = false
        },
        handleCloseForm() {
            // this.$refs.form.resetForm()
            this.formVisible = false
        },
        async openFile(folderId) {
            console.log("🚀 ~ folderId:", folderId)
            this.uploadingFiles = []
            if (folderId) {
                const api = window.$crud(`system/annexesfile/${folderId}/list`);
                const list = await this.$awaitWraper(api.getInfo());
                if (list.length) {
                    this.uploadingFiles = list.map(t => {
                        const point = {
                            ...t
                        };
                        const fileIcon = this.lr_getFileIcon(t.name);

                        point.icon = fileIcon.icon;
                        point.color = fileIcon.color;
                        point.name = point.f_FileName;
                        point.uid = point.f_Id;
                        point.id = point.f_Id;
                        point.isSuccess = true;

                        return point;
                    });
                    this.loadVisible = true
                    return
                }
            }
            this.$message.error('未查询到可预览文件资源');
        },
        handleFilePreview(uid) {
            console.log("🚀 ~ uid:", uid)
            const file = this.uploadingFiles.find(t => t.uid == uid);
            this.handlePreview(file);
        },
        downFile(fileId) {
            this.$downFile(`${this.apiUrl}system/annexesfile/${fileId}?token=${this.token}`);
        },
        handlePreview(file) {
            // if (file.isPreview == false && !this.isImg) {
            //   this.$message({
            //     type: "warning",
            //     message: "级别不够，无权限预览！"
            //   });
            //   return;
            // }
            this.isFile = true
            const fileExt = file.name.split(".")[file.name.split(".").length - 1];
            console.log(fileExt);
            this.fileExt = fileExt;
            const fileId = file.id || file.response.fileId;
            switch (fileExt.toLowerCase()) {
                // case "xls":
                // case "xlsx":
                // case "ppt":
                // case "pptx":
                // case "txt":
                // case "csv":
                // case "html":
                // case "dxf":
                case "doc":
                case "docx":
                case "pdf":
                    this.isFile = true
                    if (this.$validatenull(this.apiUrl)) {
                        return;
                    }
                    this.previewUrl = `${this.apiUrl}system/annexesfile/preview/${fileId}?token=${this.token}`;
                    this.previewFileId = fileId;
                    this.previewVisible = true;
                    break;
                // case "jpg":
                // case "gif":
                // case "png":
                // case "bmp":
                // case "jpeg":
                // case "svg":
                //     this.isFile = false
                //     if (this.isImg) {
                //         if (file.url) {
                //             this.previewUrl = file.url;
                //         } else {
                //             if (this.$validatenull(this.apiUrl)) {
                //                 return;
                //             }
                //             this.previewUrl = `${this.apiUrl}system/annexesfile/preview/${fileId}?token=${this.token}`;
                //         }
                //         this.previewVisible = true;
                //     } else {
                //         if (this.$validatenull(this.apiUrl)) {
                //             return;
                //         }
                //         this.previewUrl = `${this.apiUrl}system/annexesfile/preview/${fileId}?token=${this.token}`;
                //         this.previewFileId = fileId;
                //         this.previewVisible = true;
                //         break;
                //     }
                //     break;
                default:
                    // 不支持预览，就直接下载
                    // this.$message.warning(`当前文件格式不支持预览${fileExt}`);
                    // if (this.$validatenull(this.apiUrl)) {
                    //     return;
                    // }
                    // this.downFile(
                    //     `${this.apiUrl}system/annexesfile/${fileId}?token=${this.token}`
                    // );
                    break;
            }
        },
    }
}
</script>
<style lang="scss" scoped>
::v-deep .l-rblock {
    overflow: hidden;
}

.desc {
    width: 90%;
    height: 40px;
    box-sizing: border-box;
    line-height: 40px;
    border: 1px solid #ffe9a2;
    margin: 0 auto;
    margin-top: 20px;
    padding-left: 20px;
    background-color: #fffbe6;
    display: flex;
    align-items: center;

    .icon {
        display: flex;
        align-items: center;
        margin-right: 5px;
    }
}
</style>